package com.teen9g.infoplatformserver.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.teen9g.PageQueryDTO.AdvicePageQueryDTO;
import com.teen9g.constant.AdviceConstant;
import com.teen9g.context.BaseContext;
import com.teen9g.dto.AdviceDTO;
import com.teen9g.entity.Advice;
import com.teen9g.entity.AdviceLike;
import com.teen9g.infoplatformserver.mapper.AdviceMapper;
import com.teen9g.infoplatformserver.service.AdviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class AdviceServiceImpl implements AdviceService {

    @Autowired
    private AdviceMapper adviceMapper;

    /**
     * 分页查询建议列表
     *
     * @param advicePageQueryDTO 分页查询参数
     * @return 建议列表
     */
    @Override
    public PageInfo<Advice> page(AdvicePageQueryDTO advicePageQueryDTO) {
        PageHelper.startPage
                (advicePageQueryDTO.getPageNum(), advicePageQueryDTO.getPageSize());
        String adviceCategory = advicePageQueryDTO.getAdviceCategory();
        String adviceAuthor = advicePageQueryDTO.getAdviceAuthor();
        String adviceStatus = advicePageQueryDTO.getAdviceStatus();
        String adviceContent = advicePageQueryDTO.getAdviceContent();
        Integer order = advicePageQueryDTO.getOrder();
        List<Advice> advice =
                adviceMapper.getByPage(adviceCategory, adviceAuthor, adviceStatus, adviceContent, order);
        return new PageInfo<>(advice);
    }

    /**
     * 添加建议
     *
     * @param adviceDTO 建议DTO
     * @return 结果
     */
    @Override
    public String add(AdviceDTO adviceDTO) {
        Advice advice = Advice.builder()
                .adviceAuthor(BaseContext.getCurrentUser())
                .userId(BaseContext.getCurrentUserId())
                .adviceCategory(adviceDTO.getAdviceCategory())
                .adviceContent(adviceDTO.getAdviceContent())
                .adviceLike(0)
                .adviceStatus(AdviceConstant.ADVICE_STATUS_UNRESOLVED)
                .adviceRemark(null)
                .adviceCreateTime(LocalDateTime.now())
                .adviceUpdateTime(LocalDateTime.now())
                .build();
        int result = adviceMapper.insert(advice);
        return result > 0 ?
                AdviceConstant.ADVICE_ADD_SUCCESS : AdviceConstant.ADVICE_ADD_FAILED;
    }

    /**
     * 更新建议
     *
     * @param adviceDTO 建议DTO
     * @return 结果
     */
    @Override
    public String update(AdviceDTO adviceDTO, Integer id) {
        //判断建议条目是否存在
        Advice advice = adviceMapper.selectById(id);
        if (advice == null) {
            return AdviceConstant.ADVICE_NOT_FOUND;
        }
        //判断是否是作者
        if (!advice.getAdviceAuthor().equals(BaseContext.getCurrentUser())) {
            return AdviceConstant.ADVICE_NOT_AUTHOR;
        }
        //判断建议条目的状态（只要不是未处理状态，就不能更新）
        if (!advice.getAdviceStatus().equals
                (AdviceConstant.ADVICE_STATUS_UNRESOLVED)) {
            return AdviceConstant.ADVICE_STATUS_NOT_ALLOWED;
        }
        //更新建议条目
        advice.setAdviceCategory(adviceDTO.getAdviceCategory());
        advice.setAdviceContent(adviceDTO.getAdviceContent());
        advice.setAdviceUpdateTime(LocalDateTime.now());
        int result = adviceMapper.updateById(advice);
        return result > 0 ?
                AdviceConstant.ADVICE_UPDATE_SUCCESS : AdviceConstant.ADVICE_UPDATE_FAILED;
    }

    /**
     * 更新建议状态（管理员限定）
     *
     * @param id 建议id
     * @return 结果
     */
    @Override
    public String updateStatus(Integer id, String status, String adviceRemark) {
        //判断建议条目是否存在
        Advice advice = adviceMapper.selectById(id);
        if (advice == null) {
            return AdviceConstant.ADVICE_NOT_FOUND;
        }
        //判断是否为管理员
        if (!BaseContext.getCurrentUser().equals("huangrunhui")) {
            return AdviceConstant.ADVICE_NOT_ADMIN;
        }
        advice.setAdviceStatus(status);
        advice.setAdviceRemark(adviceRemark);
        int result = adviceMapper.updateById(advice);
        return result > 0 ?
                AdviceConstant.ADVICE_UPDATE_STATUS_SUCCESS :
                AdviceConstant.ADVICE_UPDATE_STATUS_FAILED;
    }

    /**
     * 删除建议
     *
     * @param id 建议id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Integer id) {
        //判断建议条目是否存在
        Advice advice = adviceMapper.selectById(id);
        if (advice == null) {
            return AdviceConstant.ADVICE_NOT_FOUND;
        }
        //判断是否是作者
        if (!BaseContext.getCurrentUser().equals(advice.getAdviceAuthor())) {
            return AdviceConstant.ADVICE_NOT_AUTHOR;
        }
        try {
            //删除建议条目对应的点赞记录
            int resultLike = adviceMapper.deleteLikeById(id);

            int result = adviceMapper.deleteById(id);
            return result > 0 ?
                    AdviceConstant.ADVICE_DELETE_SUCCESS : AdviceConstant.ADVICE_DELETE_FAILED;
        } catch (Exception e) {
            log.info("删除建议条目时发生未知异常:{}", e.getMessage());
            return AdviceConstant.ADVICE_DELETE_FAILED;
        }
    }

    /**
     * 点赞/取消点赞
     *
     * @param id 建议id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String likeChange(Integer id) {
        //判断建议条目是否存在
        Advice advice = adviceMapper.selectById(id);
        if (advice == null) {
            return AdviceConstant.ADVICE_NOT_FOUND;
        }
        int userId = BaseContext.getCurrentUserId();
        //判断是否已经点赞（是否有点赞记录）
        int likeTrack = adviceMapper.selectLikeTrack(id, userId);
        if (likeTrack != 0) {
            //取消点赞
            int result = adviceMapper.deleteLikeTrack(userId, id);
            //对应的点赞数-1
            int resultLike = adviceMapper.updateLike(id, -1);
            return AdviceConstant.ADVICE_DISLIKE_SUCCESS;
        } else {
            //插入一条点赞记录
            AdviceLike adviceLike = AdviceLike.builder()
                    .adviceId(id)
                    .userId(userId)
                    .createdAt(LocalDateTime.now())
                    .build();
            adviceMapper.insertLikeTrack(adviceLike);
            //对应的点赞数+1
            adviceMapper.updateLike(id, 1);
            return AdviceConstant.ADVICE_LIKE_SUCCESS;
        }
    }

    @Override
    public Integer checkLike(Integer adviceId, Integer userId) {
        return adviceMapper.selectLikeTrack(adviceId, userId);
    }
}

